import java.io.*;
import java.util.Scanner;

public class Demo6 {
    //扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的根目录: ");
        String rootPath = scanner.next();

        System.out.println("请输入要搜索的关键字: ");
        String word = scanner.next();

        //验证输入是否合法
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("输入的根目录有误!");
            return;
        }
        if (word.isEmpty()) {
            System.out.println("输入的关键字不能为空！");
            return;
        }

        //扫描
        search(rootFile,word);

    }

    private static void search(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if (files == null) return;
        for(File file : files) {
            if (file.isFile()) {
                //进一步判定
                tryFind(file,word);
            }else if (file.isDirectory()){
                search(file,word);
            }
        }
    }

    private static void tryFind(File file, String word) {
        if (file.getName().contains(word)) {
            System.out.println(file.getAbsolutePath());
        }
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(file)){
            while (true) {
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if (n == -1) break;
                stringBuilder.append(chars,0,n);
            }
        }catch (IOException e){
            e.printStackTrace();
        }

        //判断是否含有word关键字
        if (stringBuilder.indexOf(word) >= 0){
            System.out.println("找到了"+file.getAbsolutePath());
        }else {
            return;
        }
    }
}
